<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class UploadController extends Controller
{

    //上传图片
    public function store(Request $request)
    {
        if (!$request->hasFile('image')) {
            return failReturn('缺失必要参数');
        }
        //允许上传的文件类型
        $allowed_extensions = ['jpg', 'jpeg', 'png', 'gif'];
        //上传文件最大大小，单位：M
        $max_size = 60;
        $file = $request->file('image');
        $file_ext = $file->getClientOriginalExtension();
        $file_size = $file->getSize();
        if ($file_size > $max_size * 1024 * 1024) {
            return failReturn('图片大小限制' . $max_size . 'MB');
        }
        if (!in_array(Str::lower($file_ext), $allowed_extensions)) {
            return failReturn('请上传图片文件');
        }
        try {
            $storage = Storage::disk('public');
            $file_path = 'images/' . date('Y') . '/' . date('m') . '/' . date('d');
            $file_path = $storage->put($file_path, $file);
            if ($file_path !== false) {
                return successReturn([
                    'path' => $file_path,//相对路径
                    'url' => $storage->url($file_path),//绝对路径
                ]);
            }
            return failReturn('上传失败，请重试');
        } catch (Exception $exception) {
            return failReturn('上传失败，错误信息：' . $exception->getMessage());
        }

    }
}
